import React, { useEffect, useState } from 'react'
import { Badge, Button, Drawer, Form, message, Modal, Popconfirm, Space, Table, Tag, Tooltip, Typography } from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import {
  getDictTypeList,
  addDictType,
  editDictType,
  delDictTypeById,
  getDictList,
  addDict,
  editDict,
  delDictById,
  detailDictById,
} from '@/api/dict'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './columns'
import { ITableData, ITableDataType } from './types'
import { EditFormVertical } from '@/components/CustomForm'
import { useFormEdit, useFormEditData } from './useForm'
import CustomTable from '@/components/CustomTable'
import { STATUSBAND, STATUSBANDOPTIONS } from '@/constant'
import { useNavigate } from 'react-router-dom'
import './index.less'
import { current } from '@reduxjs/toolkit'
import { PlusOutlined } from '@ant-design/icons'
import { onValuesChange } from '@/utils/onValuesChange'
const Index: React.FC = () => {
  const navigate = useNavigate()
  const [form] = useForm()
  const [FormEdit] = useForm()
  const [FormData] = useForm()
  const [isModalShow, setIsModalShow] = useState(false)
  const [isEdit, setIsEdit] = useState(false)
  const [isDataEdit, setisDataEdit] = useState(false)
  const [dataList, setdataList] = useState<any[]>([])
  const [listShow, setlistShow] = useState<boolean>(false)
  const [addDrawerShow, setAddDrawerShow] = useState<boolean>(false)
  const [ispedding, setispedding] = useState<boolean>(false)
  const [currentInfo, setcurrentInfo] = useState<ITableData>()
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(getDictTypeList, {
    form: form,
  })

  const onConfirm = async (values: any) => {
    setispedding(true)
    const dictId = FormEdit.getFieldValue('dictId')
    let res
    if (!isEdit) {
      res = await addDictType({ ...values, status: values.status ? 1 : 0 }).finally(() => setispedding(false))
    } else {
      res = await editDictType({ dictId, ...values, status: values.status ? 1 : 0 }).finally(() => setispedding(false))
    }
    if (res.code === 200) {
      message.success('操作成功')
      onCancel()
      search(params)
    }
  }
  const onConfirmData = async (values: any) => {
    setispedding(true)
    const dataId = FormData.getFieldValue('dataId')
    let res
    if (!isDataEdit) {
      res = await addDict({
        dictType: currentInfo!.dictType,
        ...values,
        dictStatus: values.dictStatus ? 1 : 0,
      }).finally(() => setispedding(false))
    } else {
      res = await editDict({
        dataId,
        dictType: currentInfo!.dictType,
        ...values,
        dictStatus: values.dictStatus ? 1 : 0,
      }).finally(() => setispedding(false))
    }
    if (res.code === 200) {
      message.success('操作成功')
      onCancelDrawer()
      getListData(currentInfo!.dictType)
    }
  }
  const onCancel = () => {
    setIsModalShow(false)
    FormEdit.resetFields()
  }
  const onEdit = (info: ITableData) => {
    FormEdit.setFieldsValue({ ...info })
    setIsEdit(true)
    setIsModalShow(true)
  }
  const onEditData = (info: ITableData) => {
    FormData.setFieldsValue({ ...info })
    setisDataEdit(true)
    setAddDrawerShow(true)
  }
  const onShowModal = async (info: ITableData) => {
    setlistShow(true)
    setcurrentInfo(info)
    await getListData(info.dictType)
  }
  const getListData = async (dictType: string) => {
    const res = await getDictList({ dictType })
    if (res.code === 200) {
      setdataList(res.data.list)
    }
  }
  const onDel = async (info: ITableData) => {
    const res = await delDictTypeById({ id: info.dictId })
    if (res.code === 200) {
      message.success('操作成功')
      search(params)
    }
  }
  const onDelData = async (info: ITableDataType) => {
    const res = await delDictById({ id: info.dataId })
    if (res.code === 200) {
      message.success('操作成功')
      getListData(currentInfo!.dictType)
    }
  }
  const handleAddData = () => {
    setisDataEdit(false)
    setAddDrawerShow(true)
  }
  const onCancelDrawer = () => {
    setAddDrawerShow(false)
    FormData.resetFields()
  }
  return (
    <PageContainer className="dict_page_wrap">
      <SearchForm
        params={params}
        form={form}
        searchConfig={[
          { label: '字典名称', name: 'dictName', type: 'Input' },
          { label: '字典类型', name: 'dictType', type: 'Input' },
          { label: '字典状态', name: 'status', type: 'Select', option: STATUSBANDOPTIONS },
        ]}
        onFinish={(vals: any) => {
          search(vals)
        }}
        onReset={() => {
          reset()
        }}
        onValuesChange={(changedValues) => onValuesChange(changedValues, ['dictName', 'dictType'], form)}
        extra={
          <div className="table_extra_flex">
            <Button
              type="primary"
              onClick={() => {
                setIsModalShow(true)
                setIsEdit(false)
              }}
              icon={<PlusOutlined />}
            >
              新建字典
            </Button>
          </div>
        }
      ></SearchForm>
      <CustomTable
        bordered
        rowKey={(row) => row.dictId}
        columns={useIndexColumns(onEdit, onShowModal, onDel, params)}
        {...tableProps}
      />
      <Drawer
        title={isEdit ? '编辑字典' : '新建字典'}
        maskClosable
        open={isModalShow}
        onClose={onCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onCancel}>取消</Button>
              <Button
                loading={ispedding}
                type="primary"
                onClick={() => FormEdit.validateFields().then((values) => onConfirm(values))}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={useFormEdit({ isEdit })}
          form={FormEdit}
          initialValues={{ status: 1 }}
          onValuesChange={(changedValues) =>
            onValuesChange(changedValues, ['dictName', 'dictType', 'remark'], FormEdit)
          }
        />
      </Drawer>
      <Modal
        wrapClassName="dict_modal_wrap"
        title="字典数据列表"
        maskClosable
        open={listShow}
        width={800}
        footer={null}
        onCancel={() => {
          setlistShow(false)
        }}
      >
        <div className="custom_table_style">
          <Space style={{ marginBottom: 12 }}>
            <Button type="primary" onClick={handleAddData}>
              新增
            </Button>
          </Space>
          <Table
            bordered
            dataSource={dataList}
            pagination={false}
            rowHoverable={false}
            rowClassName={(_, index) => {
              return index % 2 === 0 ? '' : 'zebra-row-odd'
            }}
            columns={[
              {
                title: '字典编码',
                dataIndex: 'dictCode',
                key: 'dictCode',
                align: 'center',
              },
              {
                title: '字典名称',
                dataIndex: 'dictValue',
                key: 'dictValue',
                align: 'center',
              },
              {
                title: '描述',
                dataIndex: 'remark',
                key: 'remark',
                align: 'center',
                width: 150,
                ellipsis: {
                  showTitle: false,
                },
                render: (info) => {
                  return (
                    <Tooltip placement="topLeft" title={info}>
                      {info ? info : '-'}
                    </Tooltip>
                  )
                },
              },
              {
                title: '状态',
                dataIndex: 'dictStatus',
                key: 'dictStatus',
                align: 'center',
                render: (info) => {
                  return <Badge status={info == 1 ? 'success' : 'error'} text={STATUSBAND[info] || '-'} />
                },
              },
              {
                fixed: 'right',
                title: '操作',
                align: 'center',
                render: (info) => {
                  return (
                    <Space size="large">
                      <Typography.Link
                        onClick={() => {
                          onEditData(info)
                        }}
                      >
                        编辑
                      </Typography.Link>
                      <Popconfirm
                        title={`确认删除吗？`}
                        onConfirm={() => onDelData(info)}
                        okText="确认"
                        cancelText="取消"
                      >
                        <Typography.Link>删除</Typography.Link>
                      </Popconfirm>
                    </Space>
                  )
                },
              },
            ]}
          ></Table>
        </div>
      </Modal>
      <Drawer
        title={isDataEdit ? '编辑字典数据' : '新建字典数据'}
        maskClosable
        open={addDrawerShow}
        onClose={onCancelDrawer}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onCancelDrawer}>取消</Button>
              <Button
                loading={ispedding}
                type="primary"
                onClick={() => FormData.validateFields().then((values) => onConfirmData(values))}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={useFormEditData()}
          form={FormData}
          initialValues={{ dictStatus: 1 }}
          onValuesChange={(changedValues) =>
            onValuesChange(changedValues, ['dictCode', 'dictValue', 'remark'], FormData)
          }
        />
      </Drawer>
    </PageContainer>
  )
}

export default Index
